<template>
  <view class="bg-gray-50 w-[750rpx] pb-[150rpx] box-border bgs">
    <!-- 顶部导航 -->
    <PageHeader title="编辑任务" :showBack="true" />
    

    <!-- 悬赏表单 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <!-- 支付状态提示 -->
      <view v-if="formData.pay_status !== undefined" class="mb-[30rpx] p-[20rpx] rounded-[15rpx] text-[26rpx]"
        :class="canEdit ? 'bg-blue-50 text-blue-600 border border-blue-200' : 'bg-orange-50 text-orange-600 border border-orange-200'">
        {{ canEdit ? '未支付状态：可任意修改所有信息，保存时需要支付' : '已支付状态：不可修改金额、阶段和区域，其他信息可修改' }}
      </view>
      
      <view
        class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center"
      >
        <!-- <IconFont name="edit" class="text-blue-500 mr-[15rpx]" /> -->
        <text>悬赏任务信息</text>
      </view>

      <nut-form ref="formRef" :model="formData">
        <!-- 任务标题 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务标题</text
          >
          <input
            v-model="formData.title"
            type="text"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            placeholder="请输入任务标题（50字以内）"
            
          />
        </view>

        <!-- 任务分类 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务分类</text
          >
          <view
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            @click="showCategoryPicker = true"
          >
            {{ categoryText || "请选择任务分类" }}
          </view>
          <nut-popup
            v-model:visible="showCategoryPicker"
            position="bottom"
            round
          >
            <nut-picker
              v-model="categoryValue"
              :columns="categoryOptions"
              title="请选择任务分类"
              @confirm="onCategoryConfirm"
              @cancel="showCategoryPicker = false"
            />
          </nut-popup>
        </view>

        <!-- 任务标签 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务标签</text>
          
          <!-- 标签复选框列表 -->
          <view class="flex flex-wrap gap-[16rpx]">
            <view 
              v-for="tag in industryTags" 
              :key="tag.id" 
              class="flex items-center bg-gray-50 border-2 border-gray-200 rounded-[15rpx] px-[20rpx] py-[12rpx] transition-all cursor-pointer"
              :class="selectedTags.includes(tag.id) ? 'bg-blue-50 border-blue-500 text-blue-600' : 'hover:border-gray-300'"
              @click="canEdit ? toggleTag(tag.id) : null"
            >
              <nut-checkbox 
                :model-value="selectedTags.includes(tag.id)" 
                @click.stop
                @update:model-value="(val) => canEdit ? toggleTag(tag.id) : null"
                class="mr-[8rpx] pointer-events-auto"
                :disabled="!canEdit"
              />
              <text class="text-[26rpx] flex-1" @click="canEdit ? toggleTag(tag.id) : null">{{ tag.name }}</text>
            </view>
          </view>
          
          <!-- 显示已选标签 -->
          <view v-if="selectedTags.length > 0" class="mt-[20rpx]">
            <text class="text-[24rpx] text-gray-600 mb-[12rpx] block">已选择标签：</text>
            <view class="flex flex-wrap gap-[12rpx]">
              <view 
                v-for="tagId in selectedTags" 
                :key="tagId" 
                class="flex items-center bg-blue-50 text-blue-600 px-[16rpx] py-[8rpx] rounded-[20rpx] text-[24rpx] border border-blue-100"
              >
                <text>{{ getTagName(tagId) }}</text>
                <IconFont 
                  v-if="canEdit"
                  name="close" 
                  size="8" 
                  class="ml-[8rpx] text-blue-400 cursor-pointer" 
                  @click="removeTag(tagId)" 
                />
              </view>
            </view>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务描述</text
          >
          <nut-textarea
            v-model="formData.description"
            style="height: 100%"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 min-h-[120rpx] max-h-[400rpx] box-border resize-none"
            placeholder="请详细描述任务要求、完成标准、注意事项等"
          />
        </view>

        <!-- 适合人群 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">适合人群</text>
          <view class="flex flex-wrap gap-2">
            <view 
              v-for="item in suitablePersons" 
              :key="item.id"
              class="px-3 py-1 rounded-full border transition-all duration-200"
              :class="[
                selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600',
                canEdit ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'
              ]"
              @click="selectGroup(item.id)"
            >
              <text class="text-[22rpx]">{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 截止日期 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >截止日期</text
          >
          <view
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            @click="showDatePicker = true"
          >
            {{
              formData.deadline
                ? formData.deadline
                : "请选择任务截止日期"
            }}
          </view>
          <nut-popup v-model:visible="showDatePicker" position="bottom" round>
            <nut-date-picker
              v-model="dateValue"
              title="请选择任务截止日期"
              type="date"
              :min-date="minDate"
              @confirm="onDateConfirm"
              @cancel="showDatePicker = false"
            />
          </nut-popup>
        </view>

      </nut-form>
    </view>

    <!-- 阶段悬赏设置 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <view class="flex justify-between items-center mb-[30rpx]">
        <text class="text-[32rpx] font-bold text-gray-800">阶段任务设置</text>
       
      </view>

      <view
        v-for="(stage, index) in stages"
        :key="index"
        class="bg-gray-50 rounded-[20rpx] p-[30rpx] mb-[30rpx] relative"
      >
        <!-- 删除按钮 -->
        <view class="absolute top-[20rpx] right-[20rpx] z-10">
          <IconFont
            v-if="canEditAmountAndStages && stages.length > 1"
            name="close"
            color="#000"
            size="16"
            @click="removeStage(index)"
          />
        </view>

        <view class="flex justify-between items-center mb-[20rpx]">
          <text class="text-[30rpx] font-bold text-gray-800"
            >第{{ index + 1 }}阶段</text
          >
        </view>

        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]"
            >阶段金额</text
          >
          <input
            v-model="stage.price"
            type="text"
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            :disabled="!canEditAmountAndStages"
            @input="handlePriceInput"
            @blur="calculateTotal"
          />
        </view>

        <!-- 新增的阶段周期部分 -->
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]"
            >阶段周期</text
          >
          <input
            v-model="stage.cycle"
            type="number"
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            min="0"
          />
          <text
            class="text-[28rpx] text-gray-600 ml-[20rpx] w-[80rpx] text-center"
            >天</text
          >
        </view>

        <view class="mt-[20rpx]">
          <text class="text-[28rpx] font-medium mb-[15rpx] block"
            >阶段描述</text
          >
          <input
            v-model="stage.describe"
            type="text"
            class="w-full p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="请描述本阶段任务要求"
          />
        </view>

        <!-- 添加阶段按钮 -->
        <view class="text-center mt-[20rpx] relative" v-if="canEditAmountAndStages">
          <view
            class="bg-white flex items-center justify-center bg-gray-100 active:bg-gray-200 border-1 border-solid border-gray-500 px-[20rpx] py-2 relative z-2 text-gray-500 text-[26rpx] cursor-pointer"
            @click="addStageAfter(index)"
          >
            <IconFont name="plus" class="text-[32rpx]" />添加新阶段
          </view>
        </view>
      </view>
    </view>

    <!-- 金额总计 -->
    <view
      class="bg-gradient-to-r from-blue-600 to-blue-800 text-white rounded-[25rpx] p-[30rpx] m-[30rpx] flex justify-between items-center box-border"
    >
      <text class="text-[32rpx] font-bold">任务总金额</text>
      <text class="text-[48rpx] font-bold">¥ {{ taskTotal }}</text>
    </view>

    <!-- 服务方选择 -->
    <view v-if="false"
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg mb-[30rpx] box-border"
    >
      <view class="text-[32rpx] font-bold mb-[30rpx] flex items-center">
        <!-- <IconFont name="users" class="text-[#2196F3] mr-[15rpx]" /> -->
        <text>服务方选择</text>
      </view>
      <!-- 单选框组 -->
      <nut-radio-group
        v-model="providerType"
        direction="horizontal"
        class="gap-x-[40rpx] mb-[30rpx] flex items-center"
      >
        <nut-radio
          :label="'all'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >不限</nut-radio
        >
        <nut-radio
          :label="'person'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >个人从业者</nut-radio
        >
        <nut-radio
          :label="'company'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >服务商</nut-radio
        >
      </nut-radio-group>

      <!-- 服务商列表 -->
      <view v-if="providerType === 'all' || providerType === 'company'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选服务商</view>
        <view class="grid grid-cols-2 gap-[20rpx]">
          <view
            v-for="company in companyList"
            :key="company.id"
            class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]"
          >
            <nut-checkbox
              :model-value="selectedCompanies.includes(company.id)"
              @update:model-value="(val) => handleCompanyCheck(val, company.id)"
              class="mr-[4rpx] !text-[#2196F3]"
            />
            <!-- <IconFont name="building" class="text-[36rpx] text-[#2196F3] mr-[10rpx]" /> -->
            <view class="flex-1 min-w-0">
              <text
                class="text-[28rpx] font-bold text-gray-800 truncate block"
                >{{ company.name }}</text
              >
              <text class="block text-[24rpx] text-gray-500 truncate">{{
                company.desc
              }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 个人从业者列表 -->
      <view v-if="providerType === 'all' || providerType === 'person'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选个人从业者</view>
        <view class="grid grid-cols-2 gap-[20rpx] mb-[20rpx]">
          <view
            v-for="person in personList"
            :key="person.id"
            class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]"
          >
            <nut-checkbox
              :model-value="selectedPersons.includes(person.id)"
              @update:model-value="(val) => handlePersonCheck(val, person.id)"
              class="mr-[15rpx] !text-[#2196F3]"
            />
            <IconFont
              name="user"
              class="text-[36rpx] text-[#2196F3] mr-[10rpx]"
            />
            <view class="flex-1 min-w-0">
              <text
                class="text-[28rpx] font-bold text-gray-800 truncate block"
                >{{ person.name }}</text
              >
              <text class="block text-[24rpx] text-gray-500 truncate">{{
                person.desc
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 区域选择 -->
    <view class="bg-white p-[40rpx] m-[30rpx] box-border">
      <view class="text-[32rpx] font-bold mb-[36rpx]">区域选择</view>
      <view v-if="!canEditRegion" class="mb-[20rpx] p-[15rpx] bg-gray-50 text-[24rpx] text-gray-600 rounded-[10rpx]">
        <IconFont name="info" class="mr-[8rpx]" />
        已支付任务：区域选择不可修改
      </view>
      <nut-radio-group
        v-model="formData.range"
        direction="vertical"
        class="w-full"
        :disabled="!canEditRegion"
        @change="handleChange"
      >
        <view
          v-for="item in regionOptions"
          :key="item.value"
          class="flex items-center py-[20rpx] border-b border-gray-200 last:border-b-0 text-[28rpx] transition-all"
          :class="canEditRegion ? 'cursor-pointer select-none' : 'cursor-not-allowed opacity-50'"
        >
          <nut-radio
            :label="item.range"
            class="mr-[24rpx] text-blue-600 flex items-center"
            :class="formData.range === item.range ? '!text-blue-600' : '!text-gray-400'"
          />
          <text
            :class="
              formData.range === item.range
                ? 'text-blue-600 font-bold'
                : 'text-gray-500'
            "
            >{{ item.label }}</text
          >
          <text class="ml-1 text-gray-400">（信息费{{ item.fee }}元）</text>
        </view>
      </nut-radio-group>
      <view class="text-[28rpx] mt-[24rpx]">
        当前选择：{{ getRegionTextByRange(formData.range) }}，信息费¥{{
          getRegionFeeByRange(formData.range)
        }}
      </view>
    </view>

    <!-- 保存按钮 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg text-center box-border"
    >
      <nut-button
        type="primary"
        size="large"
        class="w-full text-[36rpx] font-bold bg-gradient-to-r from-blue-600 to-blue-800 h-[96rpx]"
        @click="handleSave"
        :loading="isLoading"
      >
        <template #icon>
          <IconFont name="success" class="mr-[15rpx]" />
        </template>
        {{ formData.pay_status === 0 ? '保存并支付' : '保存修改' }}
      </nut-button>
      <text class="text-[26rpx] text-gray-600 mt-[30rpx] block">
        {{ canEditAmountAndStages ? '未支付任务：可任意修改所有信息，保存时需要支付' : '已支付任务：不可修改金额、阶段和区域，其他信息可修改' }}
      </text>
    </view>

    <!-- 地图选择器 -->
    <MapPicker
      v-model="showMapPicker"
      :default-location="defaultMapLocation"
      @confirm="handleLocationConfirm"
    />

    <!-- 流程说明 -->
    <view v-if="false"
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <text
        class="text-[32rpx] font-bold text-gray-800 mb-[30rpx] text-center block"
        >任务流程说明</text
      >

      <view class="flex flex-col gap-[30rpx]">
        <view
          v-for="(step, index) in processSteps"
          :key="index"
          class="flex items-start"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[30rpx] font-bold mr-[20rpx] flex-shrink-0"
          >
            {{ index + 1 }}
          </view>
          <view class="flex-1">
            <text
              class="text-[30rpx] font-bold text-gray-800 mb-[10rpx] block"
              >{{ step.title }}</text
            >
            <text class="text-[26rpx] text-gray-600 leading-[1.5]">{{
              step.desc
            }}</text>
          </view>
        </view>
      </view>

      <view
        class="bg-yellow-50 border-l-5 border-yellow-400 p-[20rpx] rounded-[10rpx] mt-[20rpx] text-[26rpx] text-gray-600"
      >
        <IconFont
          name="exclamation-circle"
          class="text-yellow-400 mr-[10rpx]"
        />
        如出现纠纷：任何一方可点击"我有异议"，平台将冻结该笔交易金额，双方协商一致后解锁交易并按流程核销。
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Radio as nutRadio, RadioGroup as nutRadioGroup, Checkbox as nutCheckbox } from '@nutui/nutui-taro'
import PageHeader from "@/components/PageHeader.vue";
import MapPicker from "@/components/MapPicker.vue";
import { post } from "@/utils/request";
import { getTaskType } from "@/utils/comm";

// 定义接口
interface CategoryColumn {
  update_time: null | number;
  create_time: number;
  name: string;
  id: number;
  pic: string;
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

export interface taskRequest {
  id?: number;
  city?: string;
  // 周期
  cycle?: string;
  // 截止日期
  deadline?: string;
  // 描述
  describe?: string;
  // 行业ID
  industryId?: string;
  // 纬度
  latitude?: string;
  // 经度
  longitude?: string;
  range?: string;
  // 是否上热门 0 不  1 上
  recommend?: number;
  // 主任务状态  0 发布中 1 进行中 2 待确认完成 3 确认没完成 4 确认已完成
  status?: number;
  taskStages?: TaskStageVo[];
  // 类型
  taskType?: number;
  // 标题
  title?: string;
  // 标签
  tags?: string[];
  // 邀请服务方
  userIds?: number[];
  [property: string]: any;
  pay_status?: number;
}

/**
 * 任务阶段
 *
 * TaskStageVo
 */
export interface TaskStageVo {
  // 任务周期(天)
  cycle?: number;
  // 描述
  describe?: number;
  id?: number;
  // 价格
  price?: number;
  // 任务状态  0所有  1 发布中  2 进行中 3 待确认完成 4 确认没完成 5 确认已完成(待评价) 6 已评价
  status?: number;
  // 任务ID
  taskId?: number;
  [property: string]: any;
}

// 任务ID
const taskId = ref<number>(0);
// 加载状态
const isLoading = ref<boolean>(false);

// 悬赏类型
const bountyTypes = ref([
  { name: "日结类", value: "daily", icon: "calendar-day" },
  { name: "悬赏类", value: "bounty", icon: "award" },
  { name: "招聘类", value: "recruit", icon: "briefcase" },
]);

// 招聘类型
const recruitTypes = ref([
  { name: "工厂类", value: "factory", icon: "industry" },
  { name: "特殊类", value: "special", icon: "star" },
]);

// 任务分类选项
const categoryOptions = ref<{ text: string; value: string }[]>([]);

// 流程步骤
const processSteps = ref([
  { title: "发布任务", desc: "填写任务信息并支付任务金额到平台" },
  { title: "执行方申请", desc: "平台从业者在线申请执行任务" },
  { title: "选择执行方", desc: "您可以选择申请者或邀请特定从业者" },
  { title: "开始执行", desc: "双方同意后正式开始执行任务" },
  { title: "阶段结算", desc: "每个阶段完成后单独结算该阶段金额" },
]);

// 选中状态
const selectedType = ref("daily");
const selectedRecruitType = ref("");

// 行业标签相关
const industryTags = ref<any[]>([]);
const selectedTags = ref<number[]>([]);

// 适合人群相关
const suitablePersons = ref<any[]>([]);
const selectedGroupId = ref<number>(0); // 默认为"不限"

/**
 * 获取行业标签数据
 */
const getIndustryTags = async () => {
  try {
    const res = await post("/dictionary/industry");
    console.log("行业标签数据:", res);
    if (res.code === 0) {
      industryTags.value = res.data.map((item: any) => ({
        id: item.columns.id,
        name: item.columns.name,
        pic: item.columns.pic
      }));
    }
  } catch (error) {
    console.error("获取行业标签失败:", error);
    Taro.showToast({
      title: "获取标签失败",
      icon: "none"
    });
  }
};

/**
 * 获取适合人群列表
 */
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 0, name: "不限" },
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

/**
 * 选择适合人群
 * @param groupId 人群ID
 */
const selectGroup = (groupId: number) => {
  if (!canEdit.value) return; // 如果不可编辑，直接返回
  
  selectedGroupId.value = groupId;
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

/**
 * 切换标签选择状态
 * @param tagId 标签ID
 */
const toggleTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tagId);
  }
};

/**
 * 移除标签
 * @param tagId 标签ID
 */
const removeTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  }
};

/**
 * 根据标签ID获取标签名称
 * @param tagId 标签ID
 * @returns 标签名称
 */
const getTagName = (tagId: number) => {
  const tag = industryTags.value.find(item => item.id === tagId);
  return tag ? tag.name : '';
};


const formData = reactive<taskRequest>({
  range: "1" // 设置默认区域为市级
});
// const taskStages = ref<TaskStageVo[]>([]);

// 阶段数据
const stages = ref<TaskStageVo>([
  { price: "", describe: "", cycle: "" },
  { price: "", describe: "", cycle: "" },
  { price: "", describe: "", cycle: "" },
]);

/**
 * 计算任务总金额
 * @description 只包含阶段金额总和，不包含信息费，用于显示和验证
 * @returns {string} 格式化的金额字符串
 */
const taskTotal = computed(() => {
  const stagesTotal = stages.value.reduce((total: number, stage: TaskStageVo) => {
    return total + (parseFloat(String(stage.price || 0)) || 0);
  }, 0);
  return stagesTotal.toFixed(2);
});

/**
 * 计算总金额（包含信息费）
 * @description 包含阶段金额总和和信息费，目前与taskTotal相同，保留用于兼容性
 * @returns {string} 格式化的金额字符串
 */

 const totalAmount = computed(() => {
  // 计算所有阶段价格总和
  const stagesTotal = stages.value.reduce((total: number, stage: TaskStageVo) => {
    return total + (parseFloat(String(stage.price || 0)) || 0);
  }, 0);

  // 加上单独的fee，再统一处理小数位
  return (stagesTotal + (parseFloat(String(fee.value)) || 1)).toFixed(2);
});

// 计算总周期
const totalCycle = computed(() => {
  // 遍历所有阶段，累加周期数值
  return stages.value.reduce((total, stage) => {
    // 将周期字符串转为数字，空值或非数字按0处理
    return total + (parseInt(stage.cycle, 10) || 0);
  }, 0);
});

/**
 * 计算编辑权限
 * @description 根据支付状态判断是否可以编辑任务信息
 * @returns {boolean} 是否可以编辑
 */
const canEdit = computed(() => {
  return formData.pay_status != 1;
});

/**
 * 计算是否可以编辑金额和阶段
 * @description 根据支付状态判断是否可以编辑金额和阶段信息
 * @returns {boolean} 是否可以编辑金额和阶段
 */
const canEditAmountAndStages = computed(() => {
  return formData.pay_status != 1;
});

/**
 * 计算是否可以编辑区域选择
 * @description 根据支付状态判断是否可以编辑区域选择
 * @returns {boolean} 是否可以编辑区域选择
 */
const canEditRegion = computed(() => {
  return formData.pay_status != 1;
});

// 选择类型
const selectType = (type: string) => {
  selectedType.value = type;
};

// 选择招聘类型
const selectRecruitType = (type: string) => {
  selectedRecruitType.value = type;
};

// 添加阶段
const addStage = () => {
  stages.value.push({ amount: 0, description: "" });
};

// 在指定阶段后添加新阶段
const addStageAfter = (index: number) => {
  stages.value.splice(index + 1, 0, { amount: 0, description: "" });
};

// 删除阶段
const removeStage = (index: number) => {
  if (stages.value.length > 1) {
    stages.value.splice(index, 1);
  } else {
    Taro.showToast({
      title: "至少需要保留一个阶段",
      icon: "none",
    });
  }
};

// 计算总金额
const calculateTotal = () => {
  // 触发计算，computed会自动更新
};

/**
 * 处理价格输入，支持小数
 * @description 限制只能输入数字和小数点，最多两位小数
 * @param {any} event - 输入事件对象
 */
const handlePriceInput = (event: any) => {
  const value = event.target.value;
  let cleanValue = value.replace(/[^\d.]/g, '');
  
  // 确保只有一个小数点
  const dotIndex = cleanValue.indexOf('.');
  if (dotIndex !== -1) {
    const beforeDot = cleanValue.substring(0, dotIndex);
    const afterDot = cleanValue.substring(dotIndex + 1).replace(/\./g, '');
    cleanValue = beforeDot + '.' + afterDot;
  }
  
  // 限制小数点后两位
  if (dotIndex !== -1 && cleanValue.length > dotIndex + 3) {
    cleanValue = cleanValue.substring(0, dotIndex + 3);
  }
  
  // 更新价格值
  event.target.value = cleanValue;
};

// 返回
const handleBack = () => {
  Taro.navigateBack();
};

/**
 * 获取任务详情
 */
const getTaskDetail = async () => {
  try {
    isLoading.value = true;
    const res = await post("/task/detail", { id: taskId.value });
    console.log("任务详情:", res);
    
    if (res.code === 0 && res.data?.columns) {
      const taskData = res.data.columns;
      
      // 填充表单数据
      formData.id = taskData.id;
      formData.title = taskData.title;
      formData.description = taskData.describe_str;
      // 如果没有截止日期，设置为下一个月
      formData.deadline = taskData.deadline || getNextMonthDate();
      // 同步更新dateValue，将日期字符串转换为数组格式
      dateValue.value = parseDateToArray(formData.deadline);
      formData.taskType = taskData.task_type;
      formData.city = taskData.city;
      formData.industryId = taskData.industryId;
      formData.range = taskData.range_type || "1";
      formData.recommend = taskData.recommend;
      formData.status = taskData.status;
      formData.longitude = taskData.longitude;
      formData.latitude = taskData.latitude;
      formData.pay_status = taskData.pay_status;
      // 设置适合人群
      selectedGroupId.value = taskData.groupTypes || 0;
      // 设置任务分类显示
      if (taskData.task_type) {
        categoryValue.value = [String(taskData.task_type)];
        const category = categoryOptions.value.find(
          (item) => item.value == taskData.task_type
        );
        if (category) {
          categoryText.value = category.text;
        }
      }
      
      // 设置标签 - 需要根据标签名称找到对应的ID
      if (taskData.labels) {
        const labelNames = taskData.labels.split(",").filter(tag => tag.trim());
        // 等待industryTags加载完成后，根据名称找到对应的ID
        setTimeout(() => {
          selectedTags.value = labelNames.map(labelName => {
            const tag = industryTags.value.find(item => item.name === labelName.trim());
            return tag ? tag.id : null;
          }).filter(id => id !== null);
        }, 100);
      }
      
      // 设置阶段数据
      if (taskData.taskStages && taskData.taskStages.length > 0) {
        stages.value = taskData.taskStages.map((obj:any) => {
          const stage = obj.columns
          return {
            id: stage.id,
            price: stage.price?.toString() || "",
            describe: stage.task_description?.toString() || "",
            cycle: stage.cycle?.toString() || "",
            status: stage.status,
            taskId: stage.task_id
          }
        });
      }
      
      // 设置服务方选择
      if (taskData.userIds && taskData.userIds.length > 0) {
        // 根据用户类型分别设置选中的个人和服务商
        // 这里需要根据实际数据结构调整
        selectedPersons.value = taskData.userIds.filter(id => 
          personList.value.some(person => person.id === id)
        );
        selectedCompanies.value = taskData.userIds.filter(id => 
          companyList.value.some(company => company.id === id)
        );
      }
      
      // 设置区域选择
      if (taskData.range_type) {
        formData.range = taskData.range_type || "1";
        // 根据 range_type 找到对应的区域选项
        const regionOption = regionOptions.find(item => item.range === (taskData.range_type || "1"));
        if (regionOption) {
          regionLevel.value = regionOption.value;
          fee.value = regionOption.fee;
        }
      } else {
        // 如果没有区域数据，设置默认值
        formData.range = "1"; // 默认市级
        const defaultRegion = regionOptions.find(item => item.range === "1");
        if (defaultRegion) {
          regionLevel.value = defaultRegion.value;
          fee.value = defaultRegion.fee;
        }
      }
      
      Taro.showToast({
        title: "任务详情加载成功",
        icon: "success",
      });
    } else {
      Taro.showToast({
        title: res.message || "获取任务详情失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("获取任务详情失败:", error);
    Taro.showToast({
      title: "获取任务详情失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

/**
 * 保存任务修改
 * @description 根据支付状态控制保存逻辑：
 * - pay_status === 0 (未支付)：可以修改所有信息，包括金额、阶段和区域，需要支付
 * - pay_status === 1 (已支付)：只能修改除金额、阶段和区域外的其他信息
 */
const handleSave = async () => {
  console.log("formData==", formData);
  console.log("stages==", stages.value);

  if (!formData.title) {
    Taro.showToast({
      title: "请填写任务标题",
      icon: "none",
    });
    return;
  }

  if (!formData.taskType) {
    Taro.showToast({
      title: "请选择任务分类",
      icon: "none",
    });
    return;
  }

  if (!formData.description) {
    Taro.showToast({
      title: "请填写任务描述",
      icon: "none",
    });
    return;
  }

  if (selectedTags.value.length === 0) {
    Taro.showToast({
      title: "请至少选择一个任务标签",
      icon: "none",
    });
    return;
  }

  // 已支付状态下检查金额和阶段是否被修改
  if (!canEditAmountAndStages) {
    // 这里可以添加逻辑来检查金额和阶段是否被修改
    // 由于已支付状态下这些字段被禁用，理论上不会修改
    console.log("已支付任务，跳过金额和阶段验证");
  } else {
    const total = parseFloat(taskTotal.value);
    if (total <= 0) {
      Taro.showToast({
        title: "请设置任务金额",
        icon: "none",
      });
      return;
    }
  }

  // 构建地址参数
  const buildAddressParam = () => {
    switch (regionLevel.value) {
      case 'nation':
        return '全国'
      case 'province':
        return '省份' // 编辑页面没有具体省份选择，使用通用描述
      case 'city':
        return '城市' // 编辑页面没有具体城市选择，使用通用描述
      default:
        return '未选择区域'
    }
  };

  const submitData = {
    id: formData.id,
    title: formData.title,
    taskStages: stages.value,
    taskType: formData.taskType,
    deadline: formData.deadline,
    describe: formData.description,
    cycle: totalCycle.value,
    labels: selectedTags.value.map(tagId => getTagName(tagId)).join(","),
    userIds: selectedPersons.value.concat(selectedCompanies.value),
    recommend: formData.recommend || 0,
    address: buildAddressParam(), // 添加地址参数
    groupTypes: selectedGroupId.value || 0, // 添加适合人群参数
    city: formData.city || "西门市",
    industryId: formData.industryId || "4",
    range: formData.range || "1",
    longitude: formData.longitude || "-165.9479",
    latitude: formData.latitude || "28.3201",
  };

  console.log("提交数据:", submitData);
  console.log("构建的地址参数:", buildAddressParam());
  
  // 根据支付状态决定是否需要支付
  if (formData.pay_status === 0) {
    // 未支付状态，需要支付
    Taro.showModal({
      title: "确认修改",
      content: `任务标题：${formData.title}`,
      success: async (res) => {
        if (res.confirm) {
          await saveAndPay(submitData);
        }
      },
    });
  } else {
    // 已支付状态，直接保存
    await saveTask(submitData);
  }
};

/**
 * 保存任务并支付
 * @param {any} submitData - 提交的数据
 */
const saveAndPay = async (submitData: any) => {
  try {
    isLoading.value = true;
    
    const res = await post("/task/save", submitData);
    console.log("保存结果:", res);
    
    if (res.code === 0) {
      // 支付(后端返回任务id)
      await payTask(res.data);
    } else {
      Taro.showToast({
        title: res.message || "保存失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("保存任务失败:", error);
    // Taro.showToast({
    //   title: "保存失败",
    //   icon: "none",
    // });
  } finally {
    isLoading.value = false;
  }
};

/**
 * 保存任务（已支付状态）
 * @param {any} submitData - 提交的数据
 */
const saveTask = async (submitData: any) => {
  try {
    isLoading.value = true;
    
    const res = await post("/task/save", submitData);
    console.log("更新结果:", res);
    
    if (res.code === 0) {
      Taro.showToast({
        title: "任务修改成功",
        icon: "success",
        duration: 2000,
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        Taro.navigateBack();
      }, 2000);
    } else {
      Taro.showToast({
        title: res.message || "修改失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("修改任务失败:", error);
    Taro.showToast({
      title: "修改失败",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

/**
 * 支付任务费用
 * @param {number} id - 任务ID
 */
const payTask = async (id: number) => {
  const payRes = await post("/pay/task", {
    amount: totalAmount.value,
    bid: id,
    vipType: 1,
  });
  if (payRes.code == 0) {
    doPay(payRes.data);
    Taro.showToast({
      title: `支付成功`,
      icon: "success",
      duration: 3000,
    });
  }
};

/**
 * 微信支付弹窗
 * @param {any} param - 支付参数
 */
const doPay = (param: any) => {
  (window as any).WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param: any) {
      if (param.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "支付成功！",
          icon: "success",
          duration: 2000,
        });
        // 支付成功后返回上一页
        setTimeout(() => {
          Taro.navigateBack();
        }, 2000);
      } else {
        Taro.showToast({ title: "支付失败！", icon: "error", duration: 2000 });
      }
    }
  );
};

/**
 * 服务方类型
 * @type {import('vue').Ref<'all'|'person'|'company'>}
 */
const providerType = ref<"all" | "person" | "company">("all");

/**
 * 个人从业者模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const personList = ref([
]);

/**
 * 服务商模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const companyList = ref([
]);

/**
 * 选中的个人从业者ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedPersons = ref<string[]>([]);
/**
 * 选中的服务商ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedCompanies = ref<string[]>([]);

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref("city");
/** 区域信息费映射 */
const regionFeeMap: Record<string, number> = {
  city: 1,
  province: 5,
  nation: 8,
};
/**
 * 区域选项
 * @type {Array<{value: string, label: string, fee: number}>}
 */
 const regionOptions: Array<{ value: string; label: string; fee: number, range: string }> = [
  { value: "city", label: "市级", fee: 1, range: "1" },
  { value: "province", label: "省级", fee: 5, range: "2" },
  { value: "nation", label: "全国", fee: 8, range: "3" },
];
/**
 * 获取区域文本
 * @param {any} val
 * @returns {string}
 */
function getRegionText(val: any) {
  if (val === "city") return "市级";
  if (val === "province") return "省级";
  if (val === "nation") return "全国";
  return "";
}

/**
 * 根据range值获取区域文本
 * @param {string} range
 * @returns {string}
 */
function getRegionTextByRange(range: string) {
  if (range === "1") return "市级";
  if (range === "2") return "省级";
  if (range === "3") return "全国";
  return "市级";
}

/**
 * 根据range值获取区域费用
 * @param {string} range
 * @returns {number}
 */
function getRegionFeeByRange(range: string) {
  if (range === "1") return 1;
  if (range === "2") return 5;
  if (range === "3") return 8;
  return 1;
}

// 区域价格
const fee = ref(1); //默认是区域是市级
const handleChange = (value: any) => {
  if (!canEditRegion.value) return; // 如果不可编辑，直接返回
  
  const options = regionOptions.find((item) => item.range == value);
  if (options) {
    formData.range = options.range; // 更新formData.range
    fee.value = Number(options.fee);
  }
};

const showCategoryPicker = ref(false);
const categoryValue = ref<string[]>([]);
const categoryText = ref();

// 地图选择器相关
const showMapPicker = ref(false);
const defaultMapLocation = ref({
  latitude: 39.9042,
  longitude: 116.4074,
  address: "北京市",
});
function onCategoryConfirm(val: any) {
  showCategoryPicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    categoryValue.value = [String(val.selectedValue[0])];
    categoryText.value = categoryOptions.value.find(
      (item) => item.value === String(val.selectedValue[0])
    )?.text;
    formData.taskType = val.selectedValue[0];
  }
  console.log(formData.taskType);
}

// 任务类别
getCategoryText();
function getCategoryText() {
  post("/dictionary/taskType").then((res) => {
    categoryOptions.value = res.data.map((item: CategoryItem) => ({
      text: item.columns.name,
      value: item.columns.id.toString(),
    }));
  });

  getTaskType().then((res: any) => {
    console.log("res==", res);
  });
}

// 个人从业者列表
const getPersonal = async () => {
  const res = await post("/dictionary/personal");
  console.log("==>", res);
  if (res.code == 0) {
    personList.value = res.data.map((item) => ({
      id: item.columns.id,
      name: item.columns.real_name,
      desc: item.columns.brief_introduction,
    }));
  }
};
const getMerchant = async () => {
  const res = await post("/dictionary/merchant");
  console.log("==>", res);
  if (res.code == 0) {
    companyList.value = res.data.map((item) => ({
      id: item.columns.id,
      name: item.columns.real_name,
      desc: item.columns.brief_introduction,
    }));
  }
};

// 页面加载时获取数据
onMounted(async () => {
  // 设置默认截止日期为下一个月
  if (!formData.deadline) {
    formData.deadline = getNextMonthDate();
    dateValue.value = parseDateToArray(formData.deadline);
  }
  
  // 获取路由参数中的任务ID
  const params = Taro.getCurrentInstance().router?.params;
  if (params?.taskId) {
    taskId.value = Number(params.taskId);
    console.log("编辑任务ID:", taskId.value);
    
    // 先获取基础数据
    await Promise.all([
      getPersonal(),
      getMerchant(),
      getCategoryText(),
      getIndustryTags(),
      getSuitablePersons()
    ]);
    
    // 然后获取任务详情
    await getTaskDetail();
  } else {
    Taro.showToast({
      title: "缺少任务ID参数",
      icon: "none",
    });
    setTimeout(() => {
      Taro.navigateBack();
    }, 1500);
  }
});

const showDatePicker = ref(false);
const dateValue = ref<[number, number, number]>([2024, 1, 1]);

// 最小日期（今天）
const minDate = new Date();

/**
 * 获取下一个月日期
 * @returns {string} 格式化的日期字符串 YYYY-MM-DD
 */
const getNextMonthDate = () => {
  const now = new Date();
  const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());
  
  // 处理月末日期的情况（如1月31日 -> 2月28日/29日）
  if (nextMonth.getMonth() !== (now.getMonth() + 1) % 12) {
    // 如果月份不匹配，说明是月末日期，设置为下个月的最后一天
    nextMonth.setDate(0);
  }
  
  const year = nextMonth.getFullYear();
  const month = String(nextMonth.getMonth() + 1).padStart(2, '0');
  const day = String(nextMonth.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};

/**
 * 将日期字符串转换为nut-date-picker需要的数组格式
 * @param {string} dateStr - 日期字符串 YYYY-MM-DD
 * @returns {[number, number, number]} [年, 月, 日]
 */
const parseDateToArray = (dateStr: string): [number, number, number] => {
  if (!dateStr) {
    const defaultDate = getNextMonthDate();
    const [year, month, day] = defaultDate.split('-').map(Number);
    return [year, month, day];
  }
  
  const [year, month, day] = dateStr.split('-').map(Number);
  return [year, month, day];
};

/**
 * 将nut-date-picker的数组格式转换为日期字符串
 * @param {any} val - nut-date-picker的值
 * @returns {string} 格式化的日期字符串 YYYY-MM-DD
 */
const parseArrayToDate = (val: any): string => {
  if (!val) return "";
  
  if (Array.isArray(val)) {
    const [year, month, day] = val;
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  }
  
  if (typeof val === "string") {
    if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
    if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, "-");
    return val;
  }
  
  if (val && typeof val === "object" && Array.isArray(val.selectedValue)) {
    return val.selectedValue.join("-");
  }
  
  return "";
};

function onDateConfirm(val: any) {
  showDatePicker.value = false;
  // 将nut-date-picker的值转换为日期字符串并存入formData
  formData.deadline = parseArrayToDate(val);
  // 更新dateValue以保持同步
  dateValue.value = val;
}

// 格式化日期字符串（用于显示）
function formatDate(val: any) {
  if (!val) return "";
  if (typeof val === "string") {
    if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
    if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, "-");
    return val;
  }
  if (val && typeof val === "object" && Array.isArray(val.selectedValue)) {
    return val.selectedValue.join("-");
  }
  return "";
}

const handlePersonCheck = (val: boolean, id: string) => {
  const idx = selectedPersons.value.indexOf(id);
  if (val && idx === -1) selectedPersons.value.push(id);
  if (!val && idx !== -1) selectedPersons.value.splice(idx, 1);
};
const handleCompanyCheck = (val: boolean, id: string) => {
  const idx = selectedCompanies.value.indexOf(id);
  if (val && idx === -1) selectedCompanies.value.push(id);
  if (!val && idx !== -1) selectedCompanies.value.splice(idx, 1);
};

/**
 * 处理位置确认
 */
const handleLocationConfirm = (location: any) => {
  formData.location = location.address;
  // 更新提交数据中的经纬度
  formData.longitude = location.longitude;
  formData.latitude = location.latitude;

  Taro.showToast({
    title: "位置选择成功",
    icon: "success",
  });
};

defineExpose({ handlePersonCheck, handleCompanyCheck });
</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap {
    box-shadow: none !important;
  }
  .nut-checkbox {
    margin-right: 0 !important;
  }
  .nut-radio {
    margin-right: 0 !important;
    margin-bottom: 0 !important;
  }
}

// 区域选择单选框样式
.nut-radio-group {
  .nut-radio {
    &.nut-radio--checked {
      .nut-radio__icon {
        background-color: #165DFF !important;
        border-color: #165DFF !important;
      }
    }
  }
}
</style>
